<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑短信' : '发送短信'"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="短信类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择短信类型" style="width: 100%">
              <el-option label="通知短信" value="notification" />
              <el-option label="验证码" value="verification" />
              <el-option label="营销短信" value="marketing" />
              <el-option label="告警短信" value="alarm" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发送方式" prop="sendMode">
            <el-radio-group v-model="formData.sendMode">
              <el-radio value="single">单个发送</el-radio>
              <el-radio value="batch">批量发送</el-radio>
              <el-radio value="group">群组发送</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 单个发送 -->
      <div v-if="formData.sendMode === 'single'">
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input
            v-model="formData.phoneNumber"
            placeholder="请输入手机号码"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
      </div>

      <!-- 批量发送 -->
      <div v-if="formData.sendMode === 'batch'">
        <el-form-item label="手机号码" prop="phoneNumbers">
          <el-input
            v-model="formData.phoneNumbers"
            type="textarea"
            :rows="4"
            placeholder="请输入手机号码，多个号码用逗号或换行分隔"
          />
          <div class="form-tip">
            支持逗号、分号、换行分隔，最多支持1000个号码
          </div>
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".txt,.csv,.xlsx"
            @change="handleFileChange"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持txt、csv、xlsx格式，每行一个手机号码
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </div>

      <!-- 群组发送 -->
      <div v-if="formData.sendMode === 'group'">
        <el-form-item label="选择群组" prop="groupIds">
          <el-select
            v-model="formData.groupIds"
            multiple
            placeholder="请选择发送群组"
            style="width: 100%"
          >
            <el-option
              v-for="group in groupList"
              :key="group.id"
              :label="`${group.name} (${group.memberCount}人)`"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
      </div>

      <el-form-item label="短信内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="6"
          placeholder="请输入短信内容"
          maxlength="500"
          show-word-limit
        />
        <div class="content-templates">
          <span class="template-label">常用模板：</span>
          <el-button
            v-for="template in templates"
            :key="template.id"
            size="small"
            type="primary"
            link
            @click="useTemplate(template)"
          >
            {{ template.name }}
          </el-button>
        </div>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发送时间" prop="sendTime">
            <el-radio-group v-model="formData.sendTimeType">
              <el-radio value="now">立即发送</el-radio>
              <el-radio value="scheduled">定时发送</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="formData.sendTimeType === 'scheduled'" prop="scheduledTime">
            <el-date-picker
              v-model="formData.scheduledTime"
              type="datetime"
              placeholder="选择发送时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option label="低" value="low" />
              <el-option label="普通" value="normal" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="发送设置">
        <el-checkbox-group v-model="formData.settings">
          <el-checkbox value="needReply">需要回复确认</el-checkbox>
          <el-checkbox value="retryOnFail">失败自动重试</el-checkbox>
          <el-checkbox value="deliveryReport">发送状态报告</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 预览信息 -->
    <el-card v-if="previewInfo.recipientCount > 0" shadow="never" class="preview-card">
      <template #header>
        <span>发送预览</span>
      </template>
      <div class="preview-content">
        <div class="preview-item">
          <span class="label">接收人数：</span>
          <span class="value">{{ previewInfo.recipientCount }} 人</span>
        </div>
        <div class="preview-item">
          <span class="label">短信条数：</span>
          <span class="value">{{ previewInfo.messageCount }} 条</span>
        </div>
        <div class="preview-item">
          <span class="label">预计费用：</span>
          <span class="value cost">¥{{ previewInfo.estimatedCost }}</span>
        </div>
      </div>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePreview" :loading="previewLoading">
          预览
        </el-button>
        <el-button type="success" @click="handleSubmit" :loading="submitLoading">
          {{ formData.sendTimeType === 'now' ? '立即发送' : '定时发送' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  smsData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  smsData: () => ({})
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.smsData?.id)

// 表单引用
const formRef = ref()
const uploadRef = ref()

// 加载状态
const previewLoading = ref(false)
const submitLoading = ref(false)

// 表单数据
const formData = reactive({
  type: 'notification',
  sendMode: 'single',
  phoneNumber: '',
  phoneNumbers: '',
  groupIds: [],
  content: '',
  sendTimeType: 'now',
  scheduledTime: '',
  priority: 'normal',
  settings: [],
  remark: ''
})

// 预览信息
const previewInfo = reactive({
  recipientCount: 0,
  messageCount: 0,
  estimatedCost: 0
})

// 群组列表
const groupList = ref([
  { id: 1, name: '管理员群组', memberCount: 15 },
  { id: 2, name: '值班人员', memberCount: 8 },
  { id: 3, name: '技术支持', memberCount: 12 },
  { id: 4, name: '应急联系人', memberCount: 25 }
])

// 短信模板
const templates = ref([
  { id: 1, name: '验证码模板', content: '您的验证码是{code}，请在5分钟内使用。' },
  { id: 2, name: '系统通知', content: '系统将于{time}进行维护，请提前做好准备。' },
  { id: 3, name: '水位告警', content: '水库水位已达到{level}米，请立即采取相应措施。' },
  { id: 4, name: '任务提醒', content: '您有新的工作任务，请及时查看处理。' }
])

// 表单验证规则
const formRules = {
  type: [
    { required: true, message: '请选择短信类型', trigger: 'change' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  phoneNumbers: [
    { required: true, message: '请输入手机号码', trigger: 'blur' }
  ],
  groupIds: [
    { required: true, message: '请选择发送群组', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入短信内容', trigger: 'blur' },
    { min: 1, max: 500, message: '短信内容长度在1-500个字符', trigger: 'blur' }
  ],
  scheduledTime: [
    { required: true, message: '请选择发送时间', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 监听发送方式变化，动态设置验证规则
watch(() => formData.sendMode, (newMode) => {
  // 清除之前的验证
  formRef.value?.clearValidate()
  
  // 重置相关字段
  if (newMode !== 'single') {
    formData.phoneNumber = ''
  }
  if (newMode !== 'batch') {
    formData.phoneNumbers = ''
  }
  if (newMode !== 'group') {
    formData.groupIds = []
  }
})

// 监听表单数据变化，自动计算预览信息
watch([() => formData.sendMode, () => formData.phoneNumber, () => formData.phoneNumbers, () => formData.groupIds, () => formData.content], () => {
  calculatePreview()
}, { deep: true })

// 使用模板
const useTemplate = (template: any) => {
  formData.content = template.content
}

// 处理文件上传
const handleFileChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const content = e.target?.result as string
    const phoneNumbers = content.split(/[,;\n\r]+/).filter(num => num.trim())
    formData.phoneNumbers = phoneNumbers.join('\n')
  }
  reader.readAsText(file.raw)
}

// 计算预览信息
const calculatePreview = () => {
  let recipientCount = 0
  
  if (formData.sendMode === 'single' && formData.phoneNumber) {
    recipientCount = 1
  } else if (formData.sendMode === 'batch' && formData.phoneNumbers) {
    const phoneNumbers = formData.phoneNumbers.split(/[,;\n\r]+/).filter(num => num.trim())
    recipientCount = phoneNumbers.length
  } else if (formData.sendMode === 'group' && formData.groupIds.length) {
    recipientCount = formData.groupIds.reduce((total, groupId) => {
      const group = groupList.value.find(g => g.id === groupId)
      return total + (group?.memberCount || 0)
    }, 0)
  }
  
  const messageCount = recipientCount
  const estimatedCost = messageCount * 0.1 // 假设每条短信0.1元
  
  previewInfo.recipientCount = recipientCount
  previewInfo.messageCount = messageCount
  previewInfo.estimatedCost = estimatedCost
}

// 预览
const handlePreview = async () => {
  try {
    await formRef.value?.validate()
    previewLoading.value = true
    
    // 模拟预览处理
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('预览生成成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    previewLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    if (previewInfo.recipientCount === 0) {
      ElMessage.warning('请先添加接收人')
      return
    }
    
    submitLoading.value = true
    
    // 模拟提交处理
    await mockSubmitSms(formData)
    
    ElMessage.success('短信发送成功')
    emit('success')
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    type: 'notification',
    sendMode: 'single',
    phoneNumber: '',
    phoneNumbers: '',
    groupIds: [],
    content: '',
    sendTimeType: 'now',
    scheduledTime: '',
    priority: 'normal',
    settings: [],
    remark: ''
  })
  
  previewInfo.recipientCount = 0
  previewInfo.messageCount = 0
  previewInfo.estimatedCost = 0
}

// 模拟提交API
const mockSubmitSms = (data: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true })
    }, 1500)
  })
}

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible && props.smsData?.id) {
    // 编辑模式，填充数据
    Object.assign(formData, props.smsData)
  } else if (!visible) {
    // 关闭时重置表单
    resetForm()
  }
})
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.content-templates {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.template-label {
  font-size: 12px;
  color: #666;
  margin-right: 10px;
}

.preview-card {
  margin-top: 20px;
}

.preview-content {
  display: flex;
  gap: 30px;
}

.preview-item {
  display: flex;
  align-items: center;
}

.preview-item .label {
  color: #666;
  margin-right: 8px;
}

.preview-item .value {
  font-weight: 600;
  color: #333;
}

.preview-item .value.cost {
  color: #f56c6c;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-upload__tip) {
  margin-top: 5px;
}

:deep(.el-checkbox-group .el-checkbox) {
  margin-right: 20px;
}
</style>